package com.sunday.volunteer.ui.mine;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ImageUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.member.base.BaseActivity;
import com.sunday.volunteer.BaseApp;
import com.sunday.volunteer.R;
import com.sunday.volunteer.entity.Member;
import com.sunday.volunteer.http.HttpClient;
import com.sunday.volunteer.utils.BaseUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by admin on 2017/1/13.
 */

public class VolunteerCardActivity extends BaseActivity{

    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.logo)
    ImageView logo;
    @Bind(R.id.number)
    TextView number;
    @Bind(R.id.type)
    TextView type;
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.mobile)
    TextView mobile;

    @Bind(R.id.bitmap)
    View viewBitmap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_volunteer_card);
        ButterKnife.bind(this);
        titleText.setText("志愿者名片");

        getInfo();
    }

    private void getInfo(){
        Call<ResultDO<Member>> call = HttpClient.getHttpAdapter().getMemberDeatail(BaseApp.getInstance().getMemberId());
        call.enqueue(new Callback<ResultDO<Member>>() {
            @Override
            public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                if(response.body() == null || isFinish ){
                    return;
                }
                if(response.body().getCode() == 0 && response.body().getResult()!= null){
                    Member member = response.body().getResult();
                    setData(member);
                }else {
                    ToastUtils.showToast(mContext , response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Member>> call, Throwable t) {

            }
        });
    }

    private void setData(Member item){
        BaseUtil.setImage(logo , item.getLogo() , 80 ,80);
        BaseUtil.setText(number , item.getNumber());
        BaseUtil.setText(type , item.getUserTypeStr());
        BaseUtil.setText(name , item.getName());
        BaseUtil.setText(mobile ,item.getMobile() );
    }
    private Bitmap bitmap;
    @OnClick(R.id.btn)
    void btn(){
       bitmap  = convertViewToBitmap(viewBitmap);
        if (Build.VERSION.SDK_INT >= 23){
            check();
        }else {
            Save();
        }
    }

    private void check(){
        PackageManager pkgManager = getPackageManager();

        boolean sdCardReadPermission =
                pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;
        // read phone state用于获取 imei 设备信息
        boolean phoneSatePermission =
                pkgManager.checkPermission(Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, getPackageName()) == PackageManager.PERMISSION_GRANTED;


        if (!phoneSatePermission ||!sdCardReadPermission) {
            ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS },
                    0);
        } else {
            // SDK初始化，第三方程序启动时，都要进行SDK初始化工作
            //PushManager.getInstance().initialize(this.getApplicationContext());
            Save();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 0:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED ) {
                    // SDK初始化，第三方程序启动时，都要进行SDK初始化工作
                    //PushManager.getInstance().initialize(this.getApplicationContext());
                    Save();
                } else {
                    //checkMMS();
                    show();
                }
                return;
        }
    }

    private void show(){
        final UIAlertView view = new UIAlertView(this , "温馨提示" , "权限已被关闭，是否需要重新设置" , "取消" , "确定");
        view.setClicklistener(new UIAlertView.ClickListenerInterface() {
            @Override
            public void doLeft() {
                view.dismiss();
                finish();
            }

            @Override
            public void doRight() {
                view.dismiss();
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_SETTINGS);
                startActivity(intent);
                finish();
            }
        });
        view.show();
    }

    private void Save(){
        ImageUtils.saveBitmap(bitmap , "志愿者名片.jpg");
        ToastUtils.showToast(mContext , "保存成功,请到手机存储/sunday文件夹下查看");
    }


    public Bitmap convertViewToBitmap(View view){

        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
                Bitmap.Config.ARGB_8888);
        //利用bitmap生成画布
        Canvas canvas = new Canvas(bitmap);

        //把view中的内容绘制在画布上
        view.draw(canvas);
        return bitmap;
    }
}
